package com.xiongwei.prototype.deepclone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author XiongWei
 * @date 2023/12/20
 */
public class DeepProtoType implements Cloneable {

    private String name;

    private DeepCloneableTarget deepCloneableTarget;

    @Override
    public DeepProtoType clone() throws CloneNotSupportedException {
        //完成基本类型和String类型属性的克隆
        DeepProtoType clone = (DeepProtoType) super.clone();
        //单独处理引用类型属性
        clone.deepCloneableTarget = (DeepCloneableTarget)deepCloneableTarget.clone();
        return clone;
    }

    /**
     * 通过对象序列化实现(推荐)
     * @return
     */
    public DeepProtoType deepClone() {
        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType deepClone = (DeepProtoType)ois.readObject();

            return deepClone;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getDeepCloneableTarget() {
        return deepCloneableTarget;
    }

    public void setDeepCloneableTarget(DeepCloneableTarget deepCloneableTarget) {
        this.deepCloneableTarget = deepCloneableTarget;
    }
}
